<?php
namespace app\shop\model;

use app\BaseModel;
use think\facade\Db;

class IndexCoupon extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_coupon';
    /**
     * @var array
     * 查询器
     */
    protected $append = [
        'limit_data_text',
        'end_time_text'
    ];
    /**
     * User: chenniang
     * Date: 2019-10-24 15:35
     * @return void
     * descption:转数据
     */
    public function getFullAttr($value){
        return floor($value);
    }

    /**
     * User: chenniang
     * Date: 2019-10-24 15:35
     * @return void
     * descption:转数据
     */
    public function getReduceAttr($value){
        return floor($value);
    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * 状态
     */
    public function getLimitDataTextAttr($value,$data){
        if ($data['limit_type'] == 1 && !empty($data['limit_cate'])) {
            $limit_cate = explode(',', $data['limit_cate']);
            $limit_data = Db::name('longbing_card_shop_type')->where('id', 'in', $limit_cate)->column('title');
        } elseif ($data['limit_type'] == 2 && !empty($data['limit_goods'])) {
            $limit_goods = explode(',', $data['limit_goods']);
            $limit_data = Db::name('longbing_card_goods')->where('id', 'in', $limit_goods)->column('name');
        }elseif($data['limit_type'] == 0){
            $limit_data = ['全部'];
        }
        return !empty($limit_data)?array_values($limit_data):'';
    }

    /**
     * User: chenniang
     * Date: 2019-09-08 22:18
     * @param $value
     * @param $data
     * @return string
     * descption: 转换时间
     */
    public function getEndTimeTextAttr($value,$data){

        if(isset($data['end_time_type'])&&isset($data['end_time'])&&isset($data['end_time_day'])){

            if($data['end_time_type']==0){

//                $end_time = $data['end_time']-time();
//
//                return lbGetDates($end_time);
                return date('Y-m-d H:i:s',$data['start_time']).'~'.date('Y-m-d H:i:s',$data['end_time']);

            }else{

                return $data['end_time_day'].'天后过期';
            }
        }
    }

    /**
     * Created by PhpStorm.
     * User: chenniang
     * Date: 2019-09-08
     * Time: 22:15
     * @param $dis
     * @param $where
     * @return array
     * 获取两张优惠券
     */
    public function couponListSelect($dis,$user_id,$staff_id,$page=2,$send_type=0){

        $record_id = $this->canUseCouponId($dis,$user_id,$staff_id,$send_type);

        $where[]  = ['a.id','in',$record_id];

        $wheres[] = ['a.end_time','>',time()];
        //领取方式
        $wheres[] = ['a.send_type','=',0];

        $wheres[] = ['a.end_time_type','=',1];

        $mapor[]  = ['a.company_limit','=',0];

        $mapor[]  = ['b.fans_id','=',$staff_id];

        $data    = $this->alias('a')
                  ->join('longbing_card_coupon_company c','c.coupon_id = a.id AND c.type = 0','left')
                  ->join('longbing_card_user_info b','b.company_id = c.company_id','left')

                  ->where($where)
                  ->where(function ($query) use ($mapor){
                     $query->whereOr($mapor);
                  })
                    ->where(function ($query) use ($wheres){
                        $query->whereOr($wheres);
                    })
                  ->field('a.*')
                  ->group('a.id')
                  ->order('top desc,id desc')
                  ->limit($page)
                  ->select()
                  ->toArray();


        if(!empty($data)){

            foreach ($data as &$v){

                $v['record_status'] = '0';
            }
        }
        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-20 14:16
     * @功能说明:
     */
    public function companyCouponList(){


    }

    /**
     * User: chenniang
     * Date: 2019-09-20 19:45
     * @param $coupon_dis
     * @param $user_id
     * @param $staff_id
     * @return array|\think\Collection
     * descption:获取可以使用|未被领取|未领取完成的福报id
     */
    public function canUseCouponId($coupon_dis,$user_id,$staff_id,$send_type=0){

        $data = Db::name('longbing_card_coupon')
            ->where(['send_type'=>$send_type])
            ->where($coupon_dis)
            ->where('id','not in',function ($query)use ($user_id,$staff_id){
                $query->name('longbing_card_coupon_record')->where(['user_id'=>$user_id,'staff_id'=>$staff_id])->field('coupon_id');
            })
            ->field('number,id,time_limit,get_time,get_identity')
            ->select()
            ->toArray();

        if(!empty($data)){

            foreach ($data as $k=>$v){

                $count = Db::name('longbing_card_coupon_record')->where(['coupon_id'=>$v['id'],'staff_id'=>$staff_id])->count();

                if($v['number']<=$count){

                    unset($data[$k]);
                }
                //限领次数
                if($v['time_limit']==1){
                    //领取次数
                    $user_count = Db::name('longbing_card_coupon_record')->where(['coupon_id'=>$v['id'],'user_id'=>$user_id])->count();

                    if($user_count>=$v['get_time']){

                        unset($data[$k]);
                    }
                }
                //领取身份
                if($v['get_identity']==1){
                    //model
                    $user_coupon_model = new UserCoupon();
                    //该优惠券哪些用户可以领取
                    $can_user = $user_coupon_model->couponUserId(['coupon_id'=>$v['id']]);

                    if(!in_array($user_id,$can_user)){

                        unset($data[$k]);

                    }
                }
            }
        }
        $data = !empty($data)?array_column($data,'id'):['no id'];
        return $data;
    }

    /**
     * @param $dis
     * @param int $page
     * 员工端福报列表
     */
    public function staffCouponList($dis,$page=10,$where){
        $data = $this->where($dis)->where('status','>','-1')->order('id desc')->paginate($page)->toArray();
        if(!empty($data['data'])){
            foreach ($data['data'] as &$v){
                $where['coupon_id']= $v['id'];
                $v['user_number']  = Db::name('longbing_card_coupon_record')->where($where)->count();
                $v['yu_number']    = $v['number']-$v['user_number'];
                if($v['yu_number']<=0){
                    $v['status'] = 2;
                }
            }
        }
        return $data;
    }

    /**
     * @param $dis
     * @param $where
     * @return array
     * @throws \think\exception\DbException
     * 获取可领取的优惠券
     */
    public function couponListGet($dis,$user_id,$staff_id){

        $record_id = $this->canUseCouponId($dis,$user_id,$staff_id);

        $where[] = ['a.id','in',$record_id];

        $wheres[] = ['a.end_time','>',time()];

        $wheres[] = ['a.end_time_type','=',1];

        $mapor[] = ['a.company_limit','=',0];

        $mapor[] = ['b.fans_id','=',$staff_id];

        $data = $this->alias('a')
            ->join('longbing_card_coupon_company c','c.coupon_id = a.id AND c.type = 0','left')
            ->join('longbing_card_user_info b','b.company_id = c.company_id','left')
            ->where($where)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->where(function ($query) use ($wheres){
                $query->whereOr($wheres);
            })
            ->field('a.*')
            ->group('a.id')
            ->order('top desc,id desc')
            ->paginate(10)
            ->toArray();

        if(!empty($data['data'])){
            foreach ($data['data'] as &$v){
                $v['record_status'] = '0';
            }
        }

        return $data;
    }
    /**
     * @param $dis
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查看福包详情
     */
    public function couponInfo($dis,$staff_id){

        $data  = $this->where($dis)->find();

        if(!empty($data)){

            $data['user_number'] = Db::name('longbing_card_coupon_record')->where(['coupon_id'=>$data['id'],'staff_id'=>$staff_id])->count();

            $data['yu_number']   = $data['number'] - $data['user_number'];

            $data['yu_number']   = $data['yu_number']>=0?$data['yu_number'] :0 ;
        }
        return !empty($data)?$data->toArray():$data;
    }

    /**
     * @param $dis
     * @param $data
     * @return IndexCoupon
     * 修改
     */

    public function couponUpdate($dis,$data){
        $res = $this->where($dis)->update($data);
        return $res;
    }
    /**
     *
     * 修改过期的优惠状态
     */

    public function endCoupon(){
        $res = $this->where('status','<>',-1)->where('end_time','<',time())->where('end_time_type','=',0)->update(['status'=>3]);
        return $res;

    }










}